<?php

namespace Apps\Common\Libs;

use AliYun\OSS;
use PhalconPlus\Common\Component;

class UploadPic extends Component
{
    private $picType = ['image/png', 'image/jpeg'];
    /**
     * 问答的图片
     * @return array
     */
    public function questionPic()
    {
        return $this->uploadPic('question');
    }
    
    /**
     * 互动的图片
     * @return array
     */
    public function beautyParlorInteractive()
    {
        return $this->uploadPic('beauty_parlor_interactive');
    }
    /**
     * 编辑器上传图片
     * @date: 2016-1-18 
     * @author: futao
     */
	public function ueditor(){
		return $this->uploadPic('ueditor');
	}
    /**
     * 美容院封面
     * @return array
     */
    public function beautyParlorCover()
    {
        return $this->uploadPicByFile('bp_cover', 'beauty_parlor_cover');
    }
    
    /**
     * 美容院评论图片
     * @return array
     */
    public function beautyParlorComment()
    {
        return $this->uploadPic('beauty_parlor_comment');
    }

    /**
     * 美容院评多图
     * @return array
     */
    public function beautyParlorPics()
    {
        return $this->uploadPicByFile('bp_photos', 'beauty_parlor_pics');
    }

    /**
     * 活动封面
     * @return array|bool
     */
    public function activityCover()
    {
        return $this->uploadPicByFile('activity_cover', 'activity_cover');
    }

    /**
     * 活动图片
     * @return array|bool
     */
    public function activityPics()
    {
        return $this->uploadPicByFile('activity_pics', 'activity_pics');
    }
    
    /**
     * 广告封面
     * @date: 2016年1月7日
     * @author: chenxiaolin
     */
    public function advertisementPics()
    {
        return $this->uploadPicByFile('advertisement_cover', 'advertisement_cover');
    }
    
    public function bannerPics(){
        return $this -> uploadPicByFile('banner_cover', 'banner_cover');
    }

    /**
     * 用户头像
     * @return array
     */
    public function userCover()
    {
        $pics = $this->uploadPic('user_cover');
        if(is_array($pics)) {
            return $pics[0];
        }
        return $pics;
    }

    /**
     * 基础路径
     * @param $type
     * @return string
     */
    private function getBaseDir($type) {
        $dirName = '/';
        switch($type) {
            case 'question':
                $dirName = 'question/';
                break;
            case 'beauty_parlor_cover':
                $dirName = 'bp-cover/';
                break;
            case 'beauty_parlor_comment':
                $dirName = 'bp-comment/';
                break;
            case 'beauty_parlor_pics':
                $dirName = 'bp-pic/';
                break;
            case 'activity_cover':
                $dirName = 'activity-cover/';
                break;
            case 'activity_pics':
                $dirName = 'activity-pics/';
                break;
            case 'advertisement_cover':
                $dirName = 'advertisement_cover/';
                break;
            case 'user_cover':
                $dirName = 'user-cover/';
                break;
            case 'banner_pics':
                $dirName = 'banner/';
                break;
            //add by chenxiaolin
            case 'banner_cover':
                $dirName = 'banner_cover/';
                break;
            case 'ueditor':
                $dirName = 'ueditor/';
                break;
            case 'beauty_parlor_interactive':
                $dirName = 'bp-interactive/';
                break;
        }
        return $dirName;
    }
    private function uploadPic($type)
    {
        $pics = [];
        if ($this->request->hasFiles() == true) {
            $config = $this->di->get('appConfig')->aliyun->oss;
            $oss = new OSS($config->access_key, $config->secret_key, $config->hostname);
            $bucket = $config->bucket;
            // 创建目录
            $dirs = $this->getBaseDir($type) . $this->getDir();
            $this->createDir($oss, $bucket, $dirs);
            foreach ($this->request->getUploadedFiles() as $file){
                $pathExt = pathinfo($file->getName(), PATHINFO_EXTENSION);
                $ext = '.' . ($pathExt ? strtolower($pathExt) : 'jpg');
                $newFileName =  $dirs . md5(uniqid(rand(), true)) . $ext;
                $fileType = strtolower($file->getType());
                $fileType = in_array($fileType, $this->picType) ? $fileType : $this->picType[0];
                $options = [
                    OSS::OSS_CONTENT_TYPE => $fileType
                ];
                if($file->getSize() > 0) {
                    $result = $this->saveFile($oss, $bucket, $newFileName, $file->getTempName(), $options);
                    if ($result != false) {
                        $pics[] = $newFileName;
                    }
                }
                //echo $file->getName(), "<br /> ", $file->getSize(), "<br />", $file->getTempName(), "<br/>", $file->getType(),"<br /><br/> ";
            }
            /* var_dump($pics);
            exit; */
        }
        return $pics;
    }
    /**
     * 上传编辑器的图片
     * @date: 2016-1-19 
     * @author: futao
     */
    public function uploadUeditorPic($filepath,$filename){
    	$pics=[];
    	$config = $this->di->get('appConfig')->aliyun->oss;
    	$oss = new OSS($config->access_key, $config->secret_key, $config->hostname);
    	$bucket = $config->bucket;
    	$objectName = 'ueditor/'.date("Y/m/d").$filename;
    	$result = $this->saveFile($oss, $bucket, $objectName, $filepath);
    	if($result != false){
    		$pics[] = $objectName;
    	}
    	return $pics;
    }
    /**
     * 通过 $_FILES上传文件
     * @param $key
     * @param $type
     * @return array|bool
     */
    public function uploadPicByFile($key, $type)
    {
        $pics = false;
        $saveFile = function($name, $type, $tmpName, $error, $size, $dirs, $oss, $bucket){
            $pathExt = pathinfo($name, PATHINFO_EXTENSION);
            $ext = '.' . ($pathExt ? strtolower($pathExt) : 'jpg');
            $newFileName =  $dirs . md5(uniqid(rand(), true)) . $ext;
            $fileType = strtolower($type);
            $fileType = in_array($fileType, $this->picType) ? $fileType : $this->picType[0];
            $options = [
                OSS::OSS_CONTENT_TYPE => $fileType
            ];
            if($size > 0) {
                $result = $this->saveFile($oss, $bucket, $newFileName, $tmpName, $options);
                if ($result != false) {
                    return $newFileName;
                }
            }
            return false;
        };
        if($this->request->hasFiles() == true && isset($_FILES[$key])) {
            $config = $this->di->get('appConfig')->aliyun->oss;
            $oss = new OSS($config->access_key, $config->secret_key, $config->hostname);
            $bucket = $config->bucket;
            // 创建目录
            $dirs = $this->getBaseDir($type) . $this->getDir();
            $this->createDir($oss, $bucket, $dirs);
            $file = $_FILES[$key];
            $pics = [];
            if(is_string($file['name'])) {
                $url = $saveFile($file['name'], $file['type'], $file['tmp_name'], $file['error'], $file['size'], $dirs, $oss, $bucket);
                if($url !== false) {
                    $pics[] = $url;
                }
            } elseif(is_array($file['name'])) {
                for($i=0; $i<count($file['name']); $i++) {
                    $url = $saveFile($file['name'][$i], $file['type'][$i], $file['tmp_name'][$i], $file['error'][$i], $file['size'][$i], $dirs, $oss, $bucket);
                    if($url !== false) {
                        $pics[] = $url;
                    }
                }
            }
        }
        return $pics;
    }

    private function getDir()
    {
        return date("Y/m/d/H/");
    }

    /**
     * @param \AliYun\OSS $oss
     * @param string $bucket
     * @param string $dirs
     * @return bool
     */
    private function createDir($oss, $bucket, $dirs)
    {
        // TODO 上传文件到静态服务器
        $resp = $oss->create_object_dir($bucket, $dirs);
        if($resp->status == 200) {
            $this->di->get('logger')->info('oss ' . $bucket . ', 创建目录: ' . $dirs . ', response:' . json_encode($resp));
        } else {
            $this->di->get('logger')->error('oss ' . $bucket . ', 创建目录: ' . $dirs . ', response:' . json_encode($resp));
        }
        return  $resp->status == 200;
    }

    /**
     * 保存文件到 aliyun oss
     * @param \AliYun\OSS $oss
     * @param string $bucket
     * @param string $fileName
     * @param string $file
     * @param array $options
     * @return bool
     */
    private function saveFile($oss, $bucket, $fileName, $file, $options=null)
    {
        $resp = $oss->upload_file_by_file($bucket, $fileName, $file, $options);
        if($resp->status == 200) {
            $this->di->get('logger')->info('oss ' . $bucket . ', 上传文件: ' . $fileName . ', response:' . json_encode($resp));
        } else {
            $this->di->get('logger')->error('oss ' . $bucket . ', 上传文件: ' . $fileName . ', response:' . json_encode($resp));
        }
        return  $resp->status == 200;
    }
}